package popup

import android.graphics.Color
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.cardview.widget.CardView
import app.AppContext
import com.hontech.pizzav2.R
import event.ChargeStatusChangedEvent
import ext.setImageWithUrl
import manager.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import view.LoadImageView

class PayWindow : View.OnClickListener, Runnable {

    companion object {
        val Instance: PayWindow by lazy { PayWindow() }
        private val ids = intArrayOf(
            R.id.id_pay_image_view_star_1, R.id.id_pay_image_view_star_2,
            R.id.id_pay_image_view_star_3, R.id.id_pay_image_view_star_4,
            R.id.id_pay_image_view_star_5
        )
        private const val TIME_OUT = 60 * 1000L
        var isShow = false
    }

    private val view = LayoutInflater.from(AppContext).inflate(R.layout.popup_pay, null)
    private val buttonFacts = view.findViewById<Button>(R.id.id_pay_button_facts)
    private val buttonBack = view.findViewById<Button>(R.id.id_pay_button_back)
    private val layout1 = view.findViewById<LinearLayout>(R.id.id_pay_layout_1)
    private val layout2 = view.findViewById<LinearLayout>(R.id.id_pay_layout_2)
    private val imageFacts = view.findViewById<ImageView>(R.id.id_pay_image_facts)
    private val iconImageView = view.findViewById<LoadImageView>(R.id.id_pay_image)
    private val describeTextView = view.findViewById<TextView>(R.id.id_pay_text_view_describe)
    private val stars = Array<ImageView>(5) { view.findViewById(ids[it]) }
    private val textViewPrice = view.findViewById<TextView>(R.id.id_pay_text_view_price)
    private val buttonCold = view.findViewById<Button>(R.id.id_pay_button_cold)
    private val buttonHot = view.findViewById<Button>(R.id.id_pay_button_hot)
    private val cardView = view.findViewById<CardView>(R.id.id_pay_card_view)
    private val textViewPay = view.findViewById<TextView>(R.id.id_pay_text_view_pay)
    private val window = PopupWindow(
        view, WindowManager.LayoutParams.MATCH_PARENT,
        WindowManager.LayoutParams.MATCH_PARENT, true
    )

    init {
        window.animationStyle = R.style.PayTheme
        buttonCold.setOnClickListener(::onClickCold)
        buttonHot.setOnClickListener(::onClickHot)
        view.setOnClickListener(this)
        buttonFacts.setOnClickListener(::onClickFacts)
        buttonBack.setOnClickListener(::onClickBack)
        cardView.setOnClickListener { }
    }

    override fun onClick(v: View?) {
        dismiss()
    }

    private fun onClickFacts(view: View) {
        layout1.visibility = View.GONE
        layout2.visibility = View.VISIBLE
    }

    private fun onClickBack(view: View) {
        layout1.visibility = View.VISIBLE
        layout2.visibility = View.GONE
    }

    private fun onClickCold(view: View) {
//        val info = WaresManager.selectInfo()
//        describeTextView.setTextColor(Color.BLACK)
//        describeTextView.text = info.wares.descr

        DeliveryManager.isHot = false
        buttonHot.visibility = View.GONE
        buttonCold.visibility = View.GONE
        textViewPay.visibility = View.VISIBLE
        requestPay()
    }

    private fun onClickHot(view: View) {
//        val info = WaresManager.selectInfo()
//        if (info.wares.heatTempValue - StatusManager.status.ovenTempValue > 50) {
//            describeTextView.text = "Oven is not hot enough, just cold food available"
//            describeTextView.setTextColor(Color.RED)
//            return
//        }
        DeliveryManager.isHot = true
        buttonHot.visibility = View.GONE
        buttonCold.visibility = View.GONE
        textViewPay.visibility = View.VISIBLE
        requestPay()
    }

    private fun requestPay() {
        val info = WaresManager.selectInfo()
        val price = (info.wares.price * 100).toInt()
        if (price == 0) {
            EventBus.getDefault().post(ChargeStatusChangedEvent(ChargeStatusChangedEvent.OK)) // 直接支付成功
            return
        }
        PayManager.request()
    }

    private fun hotButtonCtrl() {
        val info = WaresManager.selectInfo()
        val wares = info.wares
        val h1 = wares.infraredHeatTime.toInt()
        val h2 = wares.waveHeatTime.toInt()

        if ((h1 == 0) && (h2 == 0)) {
            onClickCold(buttonCold)
        } else {
            onClickHot(buttonHot)
        }
    }

    private fun initUi() {
        val info = WaresManager.selectInfo()
        iconImageView.setImageWithUrl(info.wares.maxImageUrl)
        if (info.wares.factsImageUrl.isNotEmpty()) {
            imageFacts.setImageWithUrl(info.wares.factsImageUrl)
        } else {
            imageFacts.setImageResource(R.drawable.ic_error)
        }

        val star = info.wares.starValue
        for (i in 0 until 5) {
            if (i < star) {
                stars[i].visibility = View.VISIBLE
            } else {
                stars[i].visibility = View.GONE
            }
        }
        describeTextView.setTextColor(Color.BLACK)
        describeTextView.text = info.wares.descr

        if (MY_LOCATION == LOCATION_US) {
            textViewPrice.text = "${info.wares.name}:$${info.wares.price}"
        } else if (MY_LOCATION == LOCATION_UK) {
            textViewPrice.text = "${info.wares.name}:￡${info.wares.price}"
        }

        buttonCold.visibility = View.VISIBLE
        buttonHot.visibility = View.VISIBLE
        textViewPay.visibility = View.GONE
        textViewPay.text = "Please pay by credit card"
        layout1.visibility = View.VISIBLE
        layout2.visibility = View.GONE

        buttonCold.isEnabled = true
        buttonHot.isEnabled = true

        if (info.isAllOverdue()) {
            buttonHot.isEnabled = false
            buttonCold.isEnabled = false
            buttonHot.visibility = View.GONE
            buttonCold.visibility = View.GONE
            textViewPay.visibility = View.VISIBLE
            textViewPay.text = "The item has sold out"

            AppTask.postDelayed(this, 5 * 1000)
            return
        }
        hotButtonCtrl()
        AppTask.postDelayed(this, TIME_OUT)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onChargeStatusChangedEvent(env: ChargeStatusChangedEvent) {
        when (env.status) {
            ChargeStatusChangedEvent.ERROR -> {
                textViewPay.text = "The card reader cannot withhold money"
            }
        }
    }

    override fun run() {
        dismiss()
    }

    fun dismiss() {
        EventBus.getDefault().unregister(this)
        AppTask.removeCallbacks(this)
        PayManager.onExit()
        window.dismiss()
        AppManager.isBusy = false
        isShow = false
    }

    fun show(view: View) {
        if (isShow) {
            return
        }
        isShow = true
        AppManager.isBusy = true
        window.showAtLocation(view, Gravity.CENTER, 0, 0)
        EventBus.getDefault().register(this)
        initUi()
    }
}